package cn.uway.shiro;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.uway.cache.LocalCache;

public class MyEhcacheManager<K, V> implements CacheManager {

	protected  Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private final ConcurrentMap<String, ICache<K,V>> caches = new ConcurrentHashMap<String, ICache<K,V>>();
	
	protected net.sf.ehcache.CacheManager ehcachemanager;
	
	private LocalCache  ehcache;	
	 
	public MyEhcacheManager(net.sf.ehcache.CacheManager ehcachemanager, LocalCache  ehcache){
		this.ehcachemanager = ehcachemanager;
		this.ehcache = ehcache;
	}
	
   			
	@SuppressWarnings("unchecked")
	@Override  
    public  ICache<K, V> getCache(String name) { 		
        logger.debug("获取名称为: {}的ehcache实例", name);	
        ICache<K,V> cacheProxy = caches.get(name);		
		if (cacheProxy == null) {
			logger.info("===============getCache  ehcache={}",ehcache);			
			net.sf.ehcache.Ehcache  cache = ehcachemanager.getEhcache(name);
			if (cache == null) {
	                if (logger.isInfoEnabled()) {
	                	logger.info("Cache with name '{}' does not yet exist.  Creating now.", name);
	                }
	                this.ehcachemanager.addCache(name);

	                if (logger.isInfoEnabled()) {
	                	logger.info("Added EhCache named [" + name + "]");
	                }
	            }
	            else {
	                if (logger.isInfoEnabled()) {
	                	logger.info("Using existing EHCache named [" + cache.getName() + "]");
	                }
	        }
			// create a new cache instance
			cacheProxy = new ShiroEhcache<K, V>(ehcache, name);		
			
			// add it to the cache collection
			caches.put(name, cacheProxy);
		}
		
		return cacheProxy;
    }  	
  
}
